<template>
  <div class="generate-qrcode">
    <el-collapse-transition>
      <div v-show="!isShowManage">
        <!-- 头部 -->
        <div class="app-main-content-box">
          <div class="flexRBC">
            <div class="list-search">
              <el-input
                v-model="filterForm.taskNo"
                placeholder="请输入批次号查询"
                class="input-with-select"
                @keyup.enter.native="searchByKeyword"
              />
              <el-button
                type="primary"
                size="medium"
                round
                icon="el-icon-search"
                :loading="searchLoading"
                @click="searchByKeyword"
              >查 询</el-button>
            </div>
            <div>
              <el-button
                v-if="!$store.getters.banBtnList.includes('MCH_BTN_GENERATE_QRCODE_ADD')"
                type="primary"
                round
                size="medium"
                @click="addBatchQrcode"
              >添加批次</el-button>
            </div>
          </div>
        </div>

        <div class="app-main-content-box content">
          <!-- 筛选 -->
          <div class="app-main-filter-collapse-box">
            <el-collapse>
              <el-collapse-item title="按条件筛选" task-no="1">
                <div>
                  <el-form ref="filterForm" :model="filterForm" label-width="100px" size="small">
                    <el-form-item label="功能：" prop="taskType">
                      <el-radio-group v-model="filterForm.taskType">
                        <el-radio label="all">全部</el-radio>
                        <el-radio :label="1">点餐</el-radio>
                        <el-radio :label="2">军博游乐</el-radio>
                      </el-radio-group>
                    </el-form-item>
                    <el-form-item>
                      <el-button type="primary" round @click="submitForm('filterForm')">筛 选</el-button>
                      <el-button round @click="resetForm('filterForm')">重 置</el-button>
                    </el-form-item>
                  </el-form>
                </div>
              </el-collapse-item>
            </el-collapse>
          </div>

          <!-- 表格内容 -->
          <div class="list-table">
            <el-table
              v-loading="tableLoading"
              :data="list"
              border
              stripe
              style="width: 100%"
              size="small"
              element-loading-text="加载中"
              empty-text="暂无数据"
            >
              <el-table-column prop="taskNo" label="批次号" /> 
              <el-table-column prop="title" label="批次名称" fixed />
              <el-table-column prop="codeType" label="类型">
                <template slot-scope="scope">{{ codeTypeOptions[scope.row.codeType] }}</template>
              </el-table-column>
              <el-table-column prop="taskType" label="功能">
                <template slot-scope="scope">{{ taskTypeOptions[scope.row.taskType] }}</template>
              </el-table-column>
              <el-table-column prop="bizType" label="制码来源">
                <template slot-scope="scope">商户码</template>
              </el-table-column>
              <el-table-column prop="num" label="制作数量" />
              <el-table-column prop="bindNum" label="已绑定" />
              <el-table-column label="余量">
                <template slot-scope="scope">{{ scope.row.num-scope.row.bindNum }}</template>
              </el-table-column>
              <el-table-column prop="status" label="批次状态">
                <template slot-scope="scope">
                  <span v-if="scope.row.taskStatus===0">{{ taskStatusOptions[scope.row.taskStatus] }}</span>
                  <span
                    v-if="scope.row.taskStatus===2"
                  >{{ taskStatusOptions[scope.row.taskStatus] }}{{ scope.row.errorReason?':'+scope.row.errorReason:'' }}</span>
                  <span
                    v-if="scope.row.taskStatus===1"
                    :class="{'app-text-color-success':scope.row.taskStatus===1&&scope.row.status===1}"
                  >{{ scope.row.status===0?"已下架":"已上架" }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="createTime" label="创建时间" />
              <el-table-column label="操作" width="120" fixed="right">
                <template slot-scope="scope">
                  <el-button
                    v-if="scope.row.taskStatus===1"
                    type="text"
                    size="small"
                    @click="openManageQrcode(scope.$index, scope.row)"
                  >管理</el-button>
                  <el-button
                    v-if="!$store.getters.banBtnList.includes('MCH_BTN_GENERATE_QRCODE_MANAGE')&&scope.row.taskStatus===1"
                    type="text"
                    size="small"
                    @click="changeStatus(scope.$index, scope.row)"
                  >{{ scope.row.status===0?"上架":"下架" }}</el-button>
                </template>
              </el-table-column>
            </el-table>

            <!-- 分页 -->
            <pagination-direction
              v-if="paginationConfig.total!==0"
              :config="paginationConfig"
              @sizeschange="sizesChange"
              @pagechange="pageChange"
            />
          </div>
        </div>
      </div>
    </el-collapse-transition>

    <!-- 二维码管理 -->
    <el-collapse-transition>
      <manage-qrcode v-show="isShowManage" ref="manageQrcode" />
    </el-collapse-transition>

    <!-- 添加批次 -->
    <dialog-generate-qrcode ref="generateQrcode" />
  </div>
</template>

<script>
import ManageQrcode from './ManageQrcode'
import DialogGenerateQrcode from './DialogGenerateQrcode'
import {
  checkWxaPrefix,
  refreshWxaPrefix,
  qrcodeTaskList,
  modifyQrcodeTaskStatus
} from '@/api/wxCode'
export default {
  components: {
    ManageQrcode,
    DialogGenerateQrcode
  },
  data() {
    return {
      // 配置
      paginationConfig: {
        // 分页配置
        direction: 'center', // 分页位置
        layout: 'total, sizes, prev, pager, next, jumper', // 分页类型
        pageSizes: [10, 20], // 分页pages
        total: 0,
        page: 1, // 页数-默认1
        pageSize: 10 // 每页条数-默认10
      },
      codeTypeOptions: {
        0: '普通链接二维码'
      },
      taskTypeOptions: {
        1: '点餐桌台',
        2: '军博娱乐'
      },
      taskStatusOptions: {
        0: '正在制码',
        1: '成功',
        2: '异常'
      },
      // 状态
      tableLoading: false, // 表格loading
      searchLoading: false,
      isShowManage: false,
      // 数据
      list: [], // 表格数据
      cardList: [], // 卡列表数据
      filterForm: {
        taskNo: '',
        taskType: 'all'
      },
      filterType: 'all'
    }
  },
  mounted() {
    this.checkPrefix()
    this.initData()
  },
  methods: {
    /**
       *  获取数据
       */
    // 检查跳转规则配置
    checkPrefix() {
      checkWxaPrefix()
        .then(res => {
          if (res.data.wxaState === 0 || res.data.wxaState === 2) {
            this.refreshPrefix()
          }
        })
        .catch(() => {})
        .finally(() => {})
    },

    // 更新跳转规则
    refreshPrefix() {
      refreshWxaPrefix()
        .then(() => {})
        .catch(() => {})
        .finally(() => {})
    },

    // 获取列表
    initData(
      page = this.paginationConfig.page,
      pageSize = this.paginationConfig.pageSize
    ) {
      // 加入page
      this.filterForm.pageNum = page
      this.filterForm.pageSize = pageSize
      const params = Object.assign({}, this.filterForm)
      // 如果是key搜索
      if (this.filterType === 'key') {
        // 初始化数据
        delete params.type
      }
      delete params.date
      // 清除多余字段
      for (const key in params) {
        if (params[key] === '' || params[key] === 'all') {
          delete params[key]
        }
      }
      params.createType = 0
      this.tableLoading = true
      qrcodeTaskList(params)
        .then(res => {
          this.tableLoading = false
          this.searchLoading = false
          this.list = res.data.list
          this.paginationConfig.total = res.data.total
          this.paginationConfig.page = res.data.pageNum
        })
        .finally(() => {
          this.tableLoading = false
          this.searchLoading = false
        })
    },

    // 分页sizes改变
    sizesChange() {
      this.initData()
    },

    // 分页page改变
    pageChange() {
      this.initData()
    },

    /**
       * 按钮组
       */
    // 添加批次
    addBatchQrcode() {
      this.$refs.generateQrcode.open().then(res => {
        this.filterType = 'key'
        this.filterForm.taskNo = ''
        this.initData(1)
      })
    },

    // 点击搜索
    searchByKeyword() {
      this.searchLoading = true
      this.filterType = 'key'
      this.initData(1)
    },

    // 筛选
    submitForm() {
      this.filterType = 'all'
      this.initData(1)
    },

    //  更新状态
    changeStatus(index, row) {
      let str = ''
      let status = ''
      str = `此操作将${row.status === 0 ? '上架' : '下架'}批次：${
        row.title
      }(二维码将${row.status === 0 ? '启用' : '停用'})，是否继续?`
      status = row.status === 0 ? 1 : 0
      const params = {}
      params.status = status
      params.taskNo = row.taskNo
      this.$confirm(str, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true,
        roundButton: true
      })
        .then(() => {
          console.log(params)
          this.tableLoading = true
          modifyQrcodeTaskStatus(params)
            .then(res => {
              row.status = params.status
              this.$notify({
                title: '成功',
                message: '更新状态成功',
                type: 'success',
                duration: 2000,
                offset: 40
              })
            })
            .finally(() => {
              this.tableLoading = false
            })
        })
        .catch(() => {})
    },

    // 打开管理
    openManageQrcode(index, row) {
      this.isShowManage = true
      this.$refs.manageQrcode.open(row).then(res => {
        this.isShowManage = false
      })
    },

    // 重置
    resetForm(formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
  .generate-qrcode {
    .content {
      margin-top: 10px;
    }
    /* 搜索*/
    .list-search {
      .el-input {
        width: 40%;
        min-width: 300px;
        max-width: 500px;
        margin-right: 10px;
      }
    }
    /* 筛选 */
    .el-radio + .el-radio {
      margin-left: 0;
    }
    .el-radio {
      margin-right: 10px;
      height: 32px;
      line-height: 32px;
    }
  }
</style>
